<?php

// +----------------------------------------------------------------------
// | Shop-Demo for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2022~2023 Anyon <zoujingli@qq.com>
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// | 会员免费 ( https://thinkadmin.top/vip-introduce )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\data\controller\zck;

use app\data\model\DataPolicyExtension;
use app\data\model\DataPolicyInformation;
use app\data\model\DataZhengceku;
use app\data\model\PolicyBasics;
use app\data\model\DataZhengceku as DataNewsItem;
use app\data\service\PolicyService;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\service\AdminService;
use think\facade\Db;

/**
 * 政策内容发布
 * Class Item
 * @package app\data\controller\news
 */
class Zhengceku extends Controller
{
    /**
     * 政策库文章
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {

        $this->type   = $this->get['type'] ?? 'index';
        $this->fenlei = Db::name('data_zhengceku_fl')->where('deleted', 0)->order('sort desc')->select()->toArray();
        DataNewsItem::mQuery($this->get)->layTable(function ()
        {
            $this->title = '政策库文章';
        }, function (QueryHelper $query)
        {
            $query->like('title')->like('wzfl')->dateBetween('create_at');
            $query->where(['status' => intval($this->type === 'index'), 'deleted' => 0]);
            $admin = AdminService::getUserId();
            if ($admin != 10000) {
                $query->whereRaw("admin_id = {$admin}");
            }
        });
    }

    /**
     * 列表数据处理
     * @param  array  $data
     */
    protected function _page_filter(array &$data)
    {

        foreach ($data as &$item) {
            $item['wzfl_name'] = Db::name("data_zhengceku_fl")->where('id', $item['wzfl'])->value('name');

            if (!empty($item['qybq'])) {

                $qybq_array       = explode(',', $item['qybq']);
                $item['qybq_txt'] = '';
                $i                = 0;
                foreach ($qybq_array as $qybq_info) {
                    if ($i > 0) {
                        $item['qybq_txt'] .= ',';
                    }
                    $item['qybq_txt'] .= Db::name("data_qiye_biaoqian")->where('id', $qybq_info)->value('name');
                    $i++;
                }

            } else {
                $item['qybq_txt'] = '';
            }

            if (!empty($item['sbksrq'])) {

                $item['sbksrq'] = date('Y-m-d', $item['sbksrq']);

            } else {
                $item['sbksrq'] = '';
            }


            if ($item['riqitype'] == 1) {

                if (!empty($item['sbjzrq'])) {

                    $item['sbjzrq'] = date('Y-m-d', $item['sbjzrq']);

                } else {
                    $item['sbjzrq'] = '';
                }

            } else {

                $item['sbjzrq'] = '长期';
            }


            if (!empty($item['ctrq'])) {

                $item['ctrq'] = date('Y-m-d', $item['ctrq']);

            } else {
                $item['ctrq'] = '';
            }
            $item['is_financial_txt'] = DataZhengceku::$isFinancial[$item['is_financial'] ?? 0];
            //            if($item['wztype'] == 1){
            //                $item['wztype_txt'] = '政策公告';
            //            }else{
            //                $item['wztype_txt'] = '政策申报';
            //            }
        }

    }

    /**
     * 添加文章内容
     * @auth true
     */
    public function add()
    {
        $this->title = '添加内容';
        DataNewsItem::mForm('form');
    }

    /**
     * 编辑文章内容
     * @auth true
     */
    public function edit()
    {
        $this->title = '编辑内容';
        DataNewsItem::mForm('form');
    }

    /**
     * 表单数据处理
     * @param  array  $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if (empty($data['code'])) {//暂无code就生成一个

        }
        if ($this->request->isGet()) {
            //获取分类列表
            $this->fenlei      = Db::name('data_zhengceku_fl')->where('deleted', 0)->order('sort desc')->select()->toArray();
            $this->matter_type = Db::name('policy_matter_types')->where('deleted', 0)->select()->toArray();

            if (!empty($data['ctrq'])) {
                $data['ctrq'] = date('Y-m-d', $data['ctrq']);
            }

            if (!empty($data['sbksrq'])) {
                $data['sbksrq'] = date('Y-m-d', $data['sbksrq']);
            }

            if (!empty($data['sbjzrq'])) {
                $data['sbjzrq'] = date('Y-m-d', $data['sbjzrq']);
            }

            if (!empty($data['time_start'])) {
                $data['time_start'] = date('Y-m-d', $data['time_start']);
            }

            if (!empty($data['time_end'])) {
                $data['time_end'] = date('Y-m-d', $data['time_end']);
            }

            $newArray  = [];
            $level_map = PolicyBasics::RELEASE_LEVEL_MAP;

            foreach ($level_map as $id => $name) {
                $newArray[] = ['id' => $id, 'name' => $name];
            }
            $this->level_list = $newArray;
            if (isset($data['id'])) {
                //查询扩展表信息  补充扩展表内容
                $extension = DataPolicyExtension::query()->where('policy_id', $data['id'])->select();
                foreach ($extension as $value) {
                    $data['extension'][DataPolicyInformation::$typeMap[$value->policy_information_type]] = $value->id_set;
                    if ($value->policy_information_type == 12 && $value->id_set == 0) {
                        $data['year'] = 2;
                    } else {
                        $data['year']                    = 1;
                        $years                           = explode(',', $value->id_set);
                        $data['extension']['year_start'] = $years[0] ?? 1;
                        $data['extension']['year_end']   = $years[1] ?? 2;
                    }
                }
            }
        } else {

            //日期转换时间戳
            if (!empty($data['ctrq'])) {
                $data['ctrq'] = strtotime($data['ctrq']);
            }


            if (!empty($data['sbksrq'])) {
                $data['sbksrq'] = strtotime($data['sbksrq']);
            }


            if (!empty($data['sbjzrq'])) {
                $data['sbjzrq'] = strtotime($data['sbjzrq']);
            }

            if (!empty($data['time_start'])) {
                $data['time_start'] = strtotime($data['time_start']);
            }
            if (!empty($data['time_end'])) {
                $data['time_end'] = strtotime($data['time_end']);
            }

            //获取当前添加内容的管理员id
            $data['admin_id'] = AdminService::getUserId();

        }
    }

    /**
     * 表单结果处理
     * @param  boolean  $state
     * @param           $data
     */
    protected function _form_result(bool $state, $data)
    {
        if ($state) {
            PolicyService::instance()->handleExtended($data);
            PolicyService::instance()->createNoticeLog($data);
            $this->success('保存成功！', 'javascript:history.back()');
        }
    }

    /**
     * 修改文章状态
     * @auth true
     */
    public function state()
    {
        DataNewsItem::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除文章内容
     * @auth true
     */
    public function remove()
    {
        DataNewsItem::mDelete();
    }

    /**
     * 文章内容选择
     * @login true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function select()
    {
        $this->get['status'] = 1;
        $this->index();
    }

    public function getQybqList()
    {
        $biaoqian = Db::name('data_qiye_biaoqian')->where('deleted', 0)->select()->toArray();
        return_msg(200, 'success', $biaoqian);
    }

    public function getPolicyTypeList()
    {
        $matter_type = Db::name('data_zhengceku_fl')->where('deleted', 0)->where('status', 1)->select()->toArray();
        return_msg(200, 'success', $matter_type);
    }

    public function getMatterTypeList()
    {
        $type = Db::name('policy_matter_types')->where('deleted', 0)->where('status', 1)->select()->toArray();
        return_msg(200, 'success', $type);
    }

    public function getExtendedType()
    {
        $type    = Db::name('data_policy_information')->whereNull('deleted')->where('status', 1)->select()->toArray();
        $data    = [
            'enterprise_type'          => [],//企业类型
            'industry_classification'  => [],//行业分类
            'enterprise_scale'         => [],//企业规模
            'corporate_revenue'        => [],//企业营收
            'tax_bracket'              => [],//纳税等级
            'workers_number'           => [],//用工人数
            'develop_proportion'       => [],//研发投入占比
            'patent_number'            => [],//发明专利数量
            'soft_quantity'            => [],//软著数量
            'technical_qualifications' => [],//技术资质
            'industrial_chain_role'    => [],//产业链角色
            'establishment_period'     => [],//成立年限
        ];
        $typeMap = DataPolicyInformation::$typeMap;
        // 遍历数据并分类
        foreach ($type as $item) {
            if (isset($typeMap[(int) $item['type']])) {
                $data[$typeMap[$item['type']]][] = $item;
            }
        }
        return_msg(200, 'success', $data);
    }
}
